package com.sean.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;

public class ReferenceMain {

    public static void soft() throws InterruptedException {
        Person person = new Person("tom");
        ReferenceQueue<Person> referenceQueue = new ReferenceQueue<>();
        SoftReference<Person> softReference = new SoftReference<>(person, referenceQueue);
        System.out.println(softReference.get());
        System.out.println(referenceQueue.poll());
        person = null;
        System.gc();

        System.out.println(softReference.get());
        Thread.sleep(2000);
        System.out.println(referenceQueue.poll());

    }

    public static void weak() throws InterruptedException {
        Person person = new Person("tom");
        ReferenceQueue<Person> refQueue = new ReferenceQueue<Person>();
        WeakReference<Person> weakRef = new WeakReference<Person>(person, refQueue);
        System.out.println(weakRef.get()); // java.lang.Person@f9f9d8
        System.out.println(refQueue.poll());// null

        // 清除强引用,触发GC
        person = null;
        System.gc();

        System.out.println(weakRef.get());

        // 这里特别注意:poll是非阻塞的,remove是阻塞的.
        // JVM将弱引用放入引用队列需要一定的时间,所以这里先睡眠一会儿
        // System.out.println(refQueue.poll());// 这里有可能是null

        Thread.sleep(200);
        System.out.println(refQueue.poll());
        // System.out.println(refQueue.poll());//这里一定是null,因为已经从队列中移除

        // System.out.println(refQueue.remove());
    }

    public static void main(String[] args) throws InterruptedException {
       // ReferenceMain.soft();
        ReferenceMain.weak();
    }

}
